package controller;

import model.Activity;
import model.SignUp;
import dao.ActivityDAO;
import dao.SignUpDAO;
import util.DBUtil;
import util.ExceptionUtil;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * 活动控制器
 */
public class ActivityController {
    private ActivityDAO activityDAO;
    private SignUpDAO signUpDAO;

    public ActivityController() {
        activityDAO = new ActivityDAO();
        signUpDAO = new SignUpDAO();
    }

    // 获取所有活动
    public List<Activity> getAllActivities() {
        return activityDAO.findAllActivities();
    }

    // 获取所有报名记录
    public List<SignUp> getAllSignUps() {
        return signUpDAO.findAllSignUps();
    }

    // 根据ID获取活动
    public Activity getActivityById(String activityId) {
        return activityDAO.findActivityById(activityId);
    }

    // 根据学生ID获取报名记录
    public List<SignUp> getSignUpsByStudentId(String userId) {
        return signUpDAO.findSignUpsByUserId(userId);
    }

    // 添加活动
    public boolean addActivity(Activity activity) {
        try {
            activityDAO.addActivity(activity);
            return true;
        } catch (Exception e) {
            ExceptionUtil.handleSQLException(new SQLException("添加活动失败", e));
            return false;
        }
    }

    // 学生报名活动
    public boolean signUpActivity(String userId, String activityId) {
        return handleTransaction(() -> {
            // 检查活动是否存在
            Activity activity = activityDAO.findActivityById(activityId);
            if (activity == null) {
                System.out.println("活动不存在");
                return false;
            }

            // 检查是否已报名
            List<SignUp> userSignUps = signUpDAO.findSignUpsByUserId(userId);
            for (SignUp signUp : userSignUps) {
                if (signUp.getActivityId().equals(activityId)) {
                    System.out.println("学生已报名此活动");
                    return false;
                }
            }

            // 检查名额是否已满
            if (activity.getCurrentParticipants() >= activity.getMaxParticipants()) {
                System.out.println("活动名额已满");
                return false;
            }

            // 检查报名截止时间
            if (new java.util.Date().after(activity.getSignUpEndTime())) {
                System.out.println("报名已截止");
                return false;
            }

            // 添加报名记录
            SignUp signUp = new SignUp();
            signUp.setUserId(userId);
            signUp.setActivityId(activityId);
            signUpDAO.addSignUp(signUp);

            // 更新活动参与人数
            activity.setCurrentParticipants(activity.getCurrentParticipants() + 1);
            activityDAO.updateActivity(activity);

            return true;
        });
    }

    // 取消报名
    public boolean cancelSignUp(String userId, String activityId) {
        return handleTransaction(() -> {
            // 删除报名记录
            signUpDAO.deleteSignUp(userId, activityId);

            // 更新活动参与人数
            Activity activity = activityDAO.findActivityById(activityId);
            if (activity != null) {
                activity.setCurrentParticipants(activity.getCurrentParticipants() - 1);
                activityDAO.updateActivity(activity);
            }

            return true;
        });
    }

    private boolean handleTransaction(TransactionOperation operation) {
        Connection conn = null;
        try {
            conn = DBUtil.getConnection();
            conn.setAutoCommit(false);

            boolean result = operation.execute();

            if (result) {
                conn.commit();
            } else {
                conn.rollback();
            }

            return result;
        } catch (SQLException e) {
            ExceptionUtil.handleSQLException(e);
            try {
                if (conn != null) {
                    conn.rollback();
                }
            } catch (SQLException ex) {
                ExceptionUtil.handleSQLException(ex);
            }
            return false;
        } finally {
            DBUtil.close(conn, null, null);
        }
    }

    @FunctionalInterface
    private interface TransactionOperation {
        boolean execute() throws SQLException;
    }

    public void viewAllActivities() {
    }

    public void adminSignUpActivity() {
    }

    public void viewStudentSignedActivities() {
    }

    public void adminCancelSignUp() {

    }
}